//
//  PaymentFullVC.m
//  jiaKaoZhuShou
//
//  Created by 金艺社 on 2018/6/1.
//  Copyright © 2018年 金艺社. All rights reserved.
//

#import "PaymentFullVC.h"
#import "GKRedPacketViewController.h"
#import "CRCsnapCell.h"
#import "CRCAddresswCell.h"
#import "snapFooter.h"
#import "NetworkManager.h"
#import "driveSchoolModel.h"

#import "GKLAdressListModel.h"
#import "GKConfirmModel.h"
#import "GKLRedSelectModel.h"
@interface PaymentFullVC () <UITableViewDelegate, UITableViewDataSource> {
    driveSchoolModel *SchoolModel;
    NSString *accountBalance;//账户余额
}
@property (nonatomic, strong) UITableView *mainTable;
@property (nonatomic, copy) NSMutableArray *titleAry;
@property (nonatomic, copy) NSMutableArray *contentAry;
@property (nonatomic, strong) NSMutableArray *hongBaoList;
@property (nonatomic, strong) GKLRedSelectModel *redPacketModel; //红包数据

/// 余额不足记录需充值的金额
@property (nonatomic, assign) double userNeedRechageMoney;
@end

@implementation PaymentFullVC


- (void)viewDidLoad {
    [super viewDidLoad];
    // data
    _titleAry = [[NSMutableArray alloc]initWithArray:@[@"红包选择", @"可用余额"]];
    _contentAry = [[NSMutableArray alloc]initWithArray:@[@"暂无可用红包", @"0.00"]];
    [self requestBorrowData];
    //View
    self.title = @"确认购买";
    self.mainTable = [[UITableView alloc]initWithFrame:kScreen style:UITableViewStylePlain];
    [self.mainTable registerNib:[UINib nibWithNibName:NSStringFromClass([CRCsnapCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([CRCsnapCell class])];
    [self.mainTable registerNib:[UINib nibWithNibName:NSStringFromClass([CRCAddresswCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([CRCAddresswCell class])];
    self.mainTable.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.mainTable.delegate = self;
    self.mainTable.dataSource = self;
    self.mainTable.tableHeaderView = [[NSBundle mainBundle] loadNibNamed:@"tabHeadView" owner:nil options:nil].lastObject;
    self.mainTable.tableFooterView = [[NSBundle mainBundle] loadNibNamed:@"snapFooter" owner:nil options:nil].lastObject;
    [self.view addSubview:self.mainTable];
    
}

#pragma mark -- 获取详情数据
- (void)requestBorrowData {
    NSString *url = [NSString stringWithFormat:@"%@%@", [[apiManger shareApiManger] zhiJieZhiFuViewData], self.driveID];
    NSDictionary *parameter = @{
                                @"token" : USERTOKEN,
                                @"money" : self.money
                                };
    __weak typeof(self) weakSelf = self;
    [[NetworkManager defaultManager] check_getWithURLString:url parameters:parameter success:^(id responseObject) {
        if ([responseObject[@"rcd"] isEqualToString:kNetResponse_R0001]) {
            [weakSelf handlerBorrowData:responseObject];
        } else {
            
        }
    } failure:^(NSError *error) {
       
    }];
}

- (void)handlerBorrowData:(NSDictionary *)dic {
    SchoolModel = [driveSchoolModel mj_objectWithKeyValues:dic[@"data"]];//驾校数据
    [self headUIDrawingWith:SchoolModel]; //头部渲染
    self.hongBaoList = [GKLRedSelectModel mj_objectArrayWithKeyValuesArray:dic[@"hongbaoList"]];//红包数据
    //把购买需要的数据传到列表的底部
    snapFooter *snapV = (snapFooter *)self.mainTable.tableFooterView;
    snapV.orderId = self.ID;
    snapV.hongBaoId = self.redPacketModel.id.stringValue ? self.redPacketModel.id.stringValue : @"";
    snapV.city = SchoolModel.city;
    accountBalance = [NSString stringWithFormat:@"%@", dic[@"total"]];
    _contentAry[1] = accountBalance;
    //计算需要充值的钱
    self.userNeedRechageMoney = self.money.doubleValue - accountBalance.doubleValue;
    if (self.userNeedRechageMoney > 0.00) {
        if (self.userNeedRechageMoney < 0.01) {
            self.userNeedRechageMoney = 0.01;
        }
    }
    snapV.needChongZhi = self.userNeedRechageMoney;
    snapV.AliPayMoney = self.money.doubleValue;
    //显示红包的个数
    NSString *size = [NSString stringWithFormat:@"%@", dic[@"hongbaoSize"]];
    if (size.intValue > 0) {
        NSString *s = [NSString stringWithFormat:@"%d个红包可用", size.intValue];
        _contentAry[0] = s;
    }
    [self mainTableReloadData];
}

#pragma mark --- 跳转
- (void)didSelectHongbaoView //红包
{
    GKRedPacketViewController *redSelectVC = [[GKRedPacketViewController alloc] initWithUsableRedArray:self.hongBaoList redModel:self.redPacketModel];
    [self.navigationController pushViewController:redSelectVC animated:YES];
    __weak typeof(self)weakSelf = self;
    redSelectVC.selectedRedPacketBlock = ^(GKLRedSelectModel *model) {
        if (model) {
            weakSelf.redPacketModel = model;
            snapFooter *snapV = (snapFooter *)weakSelf.mainTable.tableFooterView;
            snapV.hongBaoId = [NSString stringWithFormat:@"%@", model.id];
            _contentAry[0] = [NSString stringWithFormat:@"¥%@", model.money];
            //计算需要充值的钱 需要支付money - 账户余额 - 红包金额 = 需要充值的money
            weakSelf.userNeedRechageMoney = weakSelf.money.doubleValue - accountBalance.doubleValue - model.money.doubleValue;
            if (weakSelf.userNeedRechageMoney > 0.00) {
                if (weakSelf.userNeedRechageMoney < 0.01) {
                    weakSelf.userNeedRechageMoney = 0.01;
                }
            }
            snapV.needChongZhi = weakSelf.userNeedRechageMoney;
            snapV.AliPayMoney = weakSelf.money.doubleValue - model.money.doubleValue;
            [weakSelf mainTableReloadData];
        } else {
            weakSelf.redPacketModel = nil;
        }
    };
}

#pragma mark --- uitableViewDataSource and delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CRCsnapCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CRCsnapCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.title_lab.text = _titleAry[indexPath.row];
    cell.content_lab.text = _contentAry[indexPath.row];
    
    if ([cell.title_lab.text isEqualToString:@"可用余额"]) {
        cell.jianTou_img.hidden = YES;
        [cell.content_lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cell.jianTou_img.mas_right);
            make.centerY.equalTo(cell.jianTou_img.mas_centerY);
        }];
    }else {
        cell.jianTou_img.hidden = NO;
    }
    
    if (self.hongBaoList.count > 0) {
        if (indexPath.row == 0) {
            cell.content_lab.textColor = [UIColor custom_color:@"#CA374F"];
        }else {
            cell.content_lab.textColor = [UIColor blackColor];
        }
    }
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self didSelectHongbaoView];
    }
}

#pragma mark --- updateUI
- (void)headUIDrawingWith:(driveSchoolModel *)model {
    UIView *head = self.mainTable.tableHeaderView.subviews.firstObject;
    for (UIView *subV in head.subviews) {
        if ([subV isKindOfClass:[UIImageView class]]) {
            UIImageView *imgV = (UIImageView *)subV;
            [imgV sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:[UIImage imageNamed:@"photo"]];
        }
        if ([subV isKindOfClass:[UILabel class]]) {
            UILabel *lab = (UILabel *)subV;
            if ([lab.text isEqualToString:@"name"]) {
                lab.text = model.companyName;
            }else if ([lab.text isEqualToString:@"time"]) {
                NSString *timeStr = [NSString ConvertStrToTime:model.createDate];
                lab.text = [timeStr substringToIndex:10];
            }else if ([lab.text isEqualToString:@"0.00"]) {
                lab.text = [NSString stringWithFormat:@"%@%@", model.money, @"元"];
            }
        }
    }
}

- (void)mainTableReloadData {
    [self.mainTable reloadData];
}

- (NSMutableArray *)hongBaoList {
    if (!_hongBaoList) {
        _hongBaoList = [NSMutableArray array];
    }
    return _hongBaoList;
}
@end
